package elsa.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import elsa.tools.UploadResp;

@Controller
public class FileUpdownController {

    /**
     * 文件上传
     */
    @CrossOrigin
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("public")
    public UploadResp upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/warehouse/";
        path=path.replaceAll("%20"," ");
        String username = request.getParameter("username");
        String filenum = request.getParameter("filenum");
        if (file.isEmpty()) {
            return UploadResp.render(0, "文件为空", "", "");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 文件上传后的路径
        String filePath = path+username+"\\"+filenum+"\\";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (dest.getParentFile().exists()) {
            File parentdest = new File(filePath);
            File[] files = parentdest.listFiles();
            for(int i =0; i<files.length; i++){
                files[i].delete();
            }
        }
        dest.getParentFile().mkdirs();
        try {
            file.transferTo(dest);
            return UploadResp.render(0,"上传成功","warehouse/"+username+"/"+filenum+"/"+fileName, fileName);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return UploadResp.render(0, "上传失败", "", "");
    }

    /**
     * 文件上传
     */
    @CrossOrigin
    @RequestMapping(value = "/uploadAll", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("public")
    public UploadResp uploadAll(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/warehouse/";
        path=path.replaceAll("%20"," ");
        String username = request.getParameter("username");
        String filenum = request.getParameter("filenum");
        if (file.isEmpty()) {
            return UploadResp.render(0, "文件为空", "", "");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 文件上传后的路径
        String filePath = path+username+"\\"+filenum+"\\";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return UploadResp.render(0,"上传成功","warehouse/"+username+"/"+filenum+"/"+fileName, fileName);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return UploadResp.render(0, "上传失败", "", "");
    }

    //文件下载
    @CrossOrigin
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("public")
    public String downloadFile(HttpServletResponse response, HttpServletRequest request){
        String fileurl = request.getParameter("file");
        if (fileurl != null) {
            String classPath = this.getClass().getClassLoader().getResource("").getPath();
            String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/";
            path=path.replaceAll("%20"," ");
            File file = new File(path, fileurl);
            String fileName = fileurl.substring(fileurl.lastIndexOf("/")+1);
            String fileName2="";
            try {
                fileName2 = new String(fileName.getBytes(), "ISO-8859-1");
            }
            catch(Exception e) {}
            if (file.exists()) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName2);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("下载成功"+fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    //文件删除
    @CrossOrigin
    @RequestMapping(value = "/deletefile", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("public")
    public String deleteF(HttpServletRequest request){
        String fileurl = request.getParameter("file");
        if (fileurl != null) {
            String classPath = this.getClass().getClassLoader().getResource("").getPath();
            String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/";
            path=path.replaceAll("%20"," ");
            File file = new File(path, fileurl);
            if(file.exists()){
                file.delete();
                return "删除成功!";
            }else {
                return "文件不存在!";
            }
        }else {
            return "文件目录错误!";
        }
    }
}